#!/data/data/com.termux/files/usr/bin/bash

export DIALOGOPTS="--clear --colors --no-collapse"
export DIALOG_OK=0
export DIALOG_CANCEL=1
export DIALOG_HELP=2
export DIALOG_ESC=255

if [[ $# -gt 0 ]]; then
  echo "Manjaroid: 不需要参数." >&2
  exit 1
elif [[ ${arch:="$(uname -m)"} != "aarch64" ]]; then
  echo "Manjaroid: 不兼容的手机架构 (${arch})."
  exit 2
elif ! command -v proot pv pulseaudio>/dev/null; then
  if (dialog --title "Manjaroid 依赖" --yesno "缺少必需的包。 你想安装它们吗？" -1 -1); then
    while true; do
      pkg install -y proot pv pulseaudio 2>&1 | dialog --title "Manjaroid 依赖" --progressbox "安装缺少的包..." -1 -1
      status=${PIPESTATUS[0]}
      if [[ ${status} != 0 ]]; then
        if (dialog --title "Manjaroid 依赖" --yesno "发生一个错误 (${status}). 要重试吗?" -1 -1); then
          continue
        fi
        exit ${status}
      fi
      break
    done
  else
    exit
  fi
fi

chroot() {
  while true; do
    directory="${1:-$(dialog --stdout --help-button --title "Manjaroid proot" --dselect "$(pwd)/manjaro" -1 -1)}"
    status=$?
    if [[ ${status} = ${DIALOG_CANCEL} || ${status} = ${DIALOG_ESC} ]]; then
      main_menu
    elif [[ ${status} = ${DIALOG_OK} && -z "${directory}" ]]; then
      dialog --title "Manjaroid proot" --msgbox "空的rootfs路径，请重试." -1 -1
      continue
    elif [[ ${status} = ${DIALOG_OK} && ! -d "${directory}" ]]; then
      dialog --title "Manjaroid proot" --msgbox "无效的rootfs路径，请重试." -1 -1
      continue
    elif [[ ${status} = ${DIALOG_HELP} ]]; then
      dialog --title "Manjaroid proot" --msgbox "指定包含有效 rootfs 的路径以 proot 进入。" -1 -1
      continue
    fi
    break
  done
  pulseaudio --load="module-native-protocol-tcp auth-ip-acl=127.0.0.1 auth-anonymous=1" --exit-idle-time=-1 --start
  unset LD_PRELOAD
  exec proot --kill-on-exit -l -0 \
    -r "${directory}" \
    -b /dev \
    -b /proc \
    -b "${directory}/root:/dev/shm" \
    -b /sdcard \
    -w /root \
    /usr/bin/env -i \
    PATH=/usr/local/sbin:/usr/local/bin:/bin:/usr/bin:/sbin:/usr/sbin:/usr/local/games:/usr/games \
    HOME=/root \
    TERM="${TERM}" \
    LANG=en_US.UTF-8 \
    LANGUAGE=en_US \
    LC_ALL=C \
    /bin/bash --login
}

setup() {
chmod -cf 755 $(find "${directory:=$1}" -type d) 2>&1 | dialog --title "Manjaro设置" --progressbox "正在更新默认目录权限..." -1 -1
while true; do
  edition="$(dialog --stdout --help-button --title "Manjaro设置" --menu "请选择一个桌面环境进行安装:" -1 -1 0 \
    0 "None" \
    1 "Xfce" \
    2 "LXQt" \
    3 "MATE (unstable)" \
    4 "i3")"
  status=$?
  if [[ ${edition} = 0 || ${status} = ${DIALOG_CANCEL} || ${status} = ${DIALOG_ESC} ]]; then
    edition=""
  elif [[ ${status} = ${DIALOG_OK} && ${edition} = 1 ]]; then
    edition="xfce"
  elif [[ ${status} = ${DIALOG_OK} && ${edition} = 2 ]]; then
    edition="lxqt"
  elif [[ ${status} = ${DIALOG_OK} && ${edition} = 3 ]]; then
    edition="mate"
  elif [[ ${status} = ${DIALOG_OK} && ${edition} = 4 ]]; then
    edition="i3"
  elif [[ ${status} = ${DIALOG_HELP} && ${edition} = "HELP 0" ]]; then
    dialog --title "Manjaro设置" --msgbox "只会安装 \Zbbase\Zn 和 \Zbsudo\Zn 包." -1 -1
    continue
  elif [[ ${status} = ${DIALOG_HELP} && ${edition} = "HELP 1" ]]; then
    dialog --title "Manjaro设置" --msgbox "安装Manjaro \ZbXfce\Zn 桌面环境" -1 -1
    continue
  elif [[ ${status} = ${DIALOG_HELP} && ${edition} = "HELP 2" ]]; then
    dialog --title "Manjaro设置" --msgbox "安装Manjaro \ZbLXQt\Zn 桌面环境" -1 -1
    continue
  elif [[ ${status} = ${DIALOG_HELP} && ${edition} = "HELP 3" ]]; then
    dialog --title "Manjaro设置" --msgbox "安装Manjaro \ZbMATE\Zn 桌面环境" -1 -1
    continue
  elif [[ ${status} = ${DIALOG_HELP} && ${edition} = "HELP 4" ]]; then
    dialog --title "Manjaro设置" --msgbox "安装Manjaro \Zbi3\Zn 窗口管理器." -1 -1
    continue
  fi
  while true; do
    username="$(dialog --stdout --title "Manjaro设置" --inputbox "请输入一个新的用户名（仅限小写字母）:" -1 -1)"
    status=$?
    if [[ ${status} = ${DIALOG_CANCEL} || ${status} = ${DIALOG_ESC} ]]; then
      continue 2
    elif [[ ${status} = ${DIALOG_OK} && -z ${username} ]]; then
      dialog --title "Manjaro设置" --msgbox "用户名不能为空，请重试" -1 -1
      continue
    fi
    password="$(dialog --stdout --insecure --title "Manjaro设置" --passwordbox "请输入用户'${username}'的密码:" -1 -1)"
    status=$?
    if [[ ${status} = ${DIALOG_CANCEL} || ${status} = ${DIALOG_ESC} ]]; then
      continue
    elif [[ ${status} = ${DIALOG_OK} && -z ${password} ]]; then
      dialog --title "Manjaro设置" --msgbox "密码不能为空，请重试" -1 -1
      continue
    fi
    break 2
  done
done
cat >"${directory}/root/.bash_profile" <<- .
## Fix common directory permissions
chmod -cf 750 /root /usr/share/polkit-1/rules.d
chmod -cf 775 /var/games
chmod -cf 555 /srv/ftp /sys
chmod -cf 1777 /tmp /var/spool/mail /var/tmp
chmod -cf 2755 /var/log/journal

## Update and install the base and sudo packages
pacman-mirrors -gf
pacman-key --init
pacman-key --populate
echo "# Configuration file for locale-gen
#
# lists of locales that are to be generated by the locale-gen command.
#
# Each line is of the form:
#
#     <locale> <charset>
#
#  where <locale> is one of the locales given in /usr/share/i18n/locales
#  and <charset> is one of the character sets listed in /usr/share/i18n/charm>
#
#  Examples:
#  en_US ISO-8859-1
#  en_US.UTF-8 UTF-8
#  de_DE ISO-8859-1
#  de_DE@euro ISO-8859-15
#
#  The locale-gen command will generate all the locales,
#  placing them in /usr/lib/locale.
#
#  A list of supported locales is included in this file.
#  Uncomment the ones you need.
#

zh_CN.UTF-8 UTF-8
zh_CN.GB18030 GB18030

">/etc/locale.gen
echo "LANG="zh_CN.UTF-8"">/etc/locale.conf
echo "nameserver 8.8.4.4">/etc/resolv.conf
cd /etc/pacman.d
rm mirrorlist
curl -O https://gitee.com/Ther-CN/TAI/raw/master/mirrorlist
pacman -Syyuu --noconfirm base sudo manjaro-release nano wqy-zenhei neofetch
locale-gen
echo 安装完成，输入exit退出，再输入bash manjaro.sh启动
neofetch
.
if [[ ! -z ${edition} ]]; then
  manjaro_packages="https://gitlab.manjaro.org/manjaro-arm/applications/arm-profiles/-/raw/master/editions/${edition}?inline=false"
  manjaro_services="https://gitlab.manjaro.org/manjaro-arm/applications/arm-profiles/-/raw/master/services/${edition}?inline=false"
  manjaro_overlays="https://gitlab.manjaro.org/manjaro-arm/applications/arm-profiles/-/archive/master/arm-profiles-master.tar?path=overlays/${edition}"
  cat >>"${directory}/root/.bash_profile" <<- .
## Install profile packages
packages=(\$(curl -sL "${manjaro_packages}" | sed -e 's/\\s*#.*//;/^\\s*$/d;s/\\s*$//'))
for package in \$(pacman -Sp "\${packages[@]}" 2>&1 | grep -Po '[^\\s]*$'); do
  packages=(\${packages[@]/\${package}})
done
pacman -S --needed --noconfirm \${packages[@]}

## Enable profile services (optional)
for service in \$(curl -sL "${manjaro_services}"); do
  systemctl enable \${service}
done

## Install profile overlays
curl -sL "${manjaro_overlays}" | \\
  tar -xvf - -C / --wildcards --exclude='overlay.txt' \\
  arm-profiles-master-overlays-${edition}/overlays/${edition}/* --strip 3
.
  if (dialog --title "Manjaro设置" --yesno "是否使用TigerVNC?" -1 -1); then
    cat >>"${directory}/root/.bash_profile" <<- .
## Setup TigerVNC
pacman -S --needed --noconfirm tigervnc

mkdir -p /etc/skel/.vnc
cat >"/etc/skel/.vnc/xstartup" <<- ...
#!/bin/sh
unset SESSION_MANAGER
export DISPLAY=":1"
export PULSE_SERVER=127.0.0.1
pulseaudio --start
[[ -r \${HOME}/.Xresources ]] && xrdb \${HOME}/.Xresources
exec dbus-launch $(
  if [[ ${edition} = "xfce" ]]; then
    echo "startxfce4"
  elif [[ ${edition} = "lxqt" ]]; then
    echo "startlxqt"
  elif [[ ${edition} = "mate" ]]; then
    echo "mate-session"
  elif [[ ${edition} = "i3" ]]; then
    echo "i3"
  fi
)
...
chmod -cf +x /etc/skel/.vnc/xstartup

cat >"/etc/skel/.vnc/config" <<- ...
Desktop=manjaro
Geometry=1024x768
SecurityTypes=VncAuth,TLSVnc
Localhost
...
.
  fi
fi
cat >>"${directory}/root/.bash_profile" <<- .
## Miscellaneous setup
paccache -rk0
chmod -cf 755 /etc /etc/fonts /usr /usr/share /usr/share/icons
mkdir -p /etc/skel/.config
echo "--no-sandbox" >"/etc/skel/.config/chromium-flags.conf"
.
cat >>"${directory}/root/.bash_profile" <<- .
## Add new user account
useradd -m -G wheel -s /bin/bash ${username}
echo "${username}:${password}" | chpasswd
sed -i -e "/root ALL=(ALL) ALL/a ${username} ALL=(ALL) ALL" \\
  -e "s/# %wheel ALL=(ALL) ALL/%wheel ALL=(ALL) ALL/" /etc/sudoers
echo "exec su - ${username}" >/root/.bash_profile
bash /root/.bash_profile
.
}

install() {
  while true; do
    directory="$(dialog --stdout --help-button --title "Manjaro 安装" --dselect "$(pwd)/manjaro" -1 -1)"
    status=$?
    if [[ ${status} = ${DIALOG_CANCEL} || ${status} = ${DIALOG_ESC} ]]; then
      main_menu
    elif [[ ${status} = ${DIALOG_OK} && -d "${directory}" ]]; then
      if (dialog --title "Manjaro 安装" --yesno "目录${directory}'已存在，是否要删除它?" -1 -1); then
        chmod -Rcf 777 "${directory}" 2>&1 | dialog --title "Manjaro 安装" --progressbox "正在更新目录'${directory}'权限..." -1 -1
        rm -rvf ${directory} 2>&1 | dialog --title "Manjaro 安装" --progressbox "移除'${directory}'..." -1 -1
      fi
    elif [[ ${status} = ${DIALOG_OK} && -z "${directory}" ]]; then
      dialog --title "Manjaro 安装" --msgbox "空的安装路径，请重试." -1 -1
      continue
    elif [[ ${status} = ${DIALOG_HELP} ]]; then
      dialog --title "Manjaro 安装" --msgbox "指定一个Manjaro安装目录." -1 -1
      continue
    fi
    mkdir -p "${directory}" 2>&1 >/dev/null
    manjaro_rootfs="https://mirrors.tuna.tsinghua.edu.cn/osdn/storage/g/m/ma/manjaro-arm/.rootfs/Manjaro-ARM-aarch64-latest.tar.gz"
    size=$(curl -sLI "${manjaro_rootfs}" | awk '/content-length/ {printf "%i", ($2/1024)/1024}')
    (curl -sL "${manjaro_rootfs}" | pv -ns "${size}m" - | proot -l tar -xzf - -C "${directory}") 2>&1 | \
      dialog --title "Manjaro 安装" --gauge "下载Manjaro-ARM-aarch64-latest.tar.gz (${size}MB)..." -1 -1
    status=${PIPESTATUS[0]}
    if [[ ${status} != 0 ]]; then
      dialog --title "Manjaro 安装" --msgbox "发生一个错误(${status}).请重试." -1 -1
      continue
    fi
    setup "${directory}"
    chroot "${directory}"
  done
}

remove() {
  while true; do
    directory="$(dialog --stdout --help-button --title "Manjaroid remove" --dselect "$(pwd)/manjaro" -1 -1)"
    status=$?
    if [[ ${status} = ${DIALOG_CANCEL} || ${status} = ${DIALOG_ESC} ]]; then
      main_menu
    elif [[ ${status} = ${DIALOG_OK} && -z "${directory}" ]]; then
      dialog --title "Manjaro移除" --msgbox "没有rootfs目录，请重试" -1 -1
      continue
    elif [[ ${status} = ${DIALOG_HELP} ]]; then
      dialog --title "Manjaro移除" --msgbox "指定包含要删除的有效rootfs的路径。." -1 -1
      continue
    fi
    if (dialog --title "Manjaro移除" --yesno "确定要移除'${directory}'吗?" -1 -1); then
      chmod -Rcf 777 "${directory}" 2>&1 | dialog --title "Manjaro移除" --progressbox "正在更新目录'${directory}'的权限..." -1 -1
      rm -rvf ${directory} 2>&1 | dialog --title "Manjaroid remove" --progressbox "移除'${directory}'中..." -1 -1
    fi
  done
}

main_menu() {
  while true; do
    menu="$(dialog --stdout --help-button --title "Manjaroid 主菜单" \
      --menu "请选择任意一项:" -1 -1 0 \
      1 "启动Manjaro arm" \
      2 "安装最新Manjro arm" \
      3 "卸载Manjaro arm")"
    status=$?
    if [[ ${status} = ${DIALOG_CANCEL} || ${status} = ${DIALOG_ESC} ]]; then
      exit ${status}
    elif [[ ${status} = ${DIALOG_OK} && ${menu} = 1 ]]; then
      chroot
    elif [[ ${status} = ${DIALOG_OK} && ${menu} = 2 ]]; then
      install
    elif [[ ${status} = ${DIALOG_OK} && ${menu} = 3 ]]; then
      remove
    elif [[ ${status} = ${DIALOG_HELP} && ${menu} = "HELP 1" ]]; then
      dialog --title "Manjaro主菜单" --msgbox "在包含有效rootfs的目标目录中执行proot。" -1 -1
      continue
    elif [[ ${status} = ${DIALOG_HELP} && ${menu} = "HELP 2" ]]; then
      dialog --title "Manjaro主菜单" --msgbox "在一个目录里安装Manjaro arm." -1 -1
      continue
    elif [[ ${status} = ${DIALOG_HELP} && ${menu} = "HELP 3" ]]; then
      dialog --title "Manjaro主菜单" --msgbox "更新权限并卸载Manjaro arm." -1 -1
      continue
    fi
  done
}

main_menu
